﻿namespace Atomic.Extensions
{
    using System;
    using System.Linq;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Threading.Tasks;

    /// <summary>
    /// 枚举器扩展
    /// </summary>
    public static class EnumerableExtensions
    {
        /// <summary>
        /// 循环执行方法。
        /// </summary>
        /// <typeparam name="TSource">对象类型。</typeparam>
        /// <param name="enumerable">对象列表。</param>
        /// <param name="action">方法。</param>
        public static void ForEach<TSource>(this IEnumerable<TSource> enumerable, Action<TSource> action)
        {
            if (enumerable != null && enumerable.Any())
            {
                foreach (TSource item in enumerable)
                {
                    action(item);
                }
            }
        }

        /// <summary>
        /// 并行循环执行方法。
        /// </summary>
        /// <typeparam name="TSource">对象类型。</typeparam>
        /// <param name="enumerable">对象列表。</param>
        /// <param name="action">方法。</param>
        public static void ForEachParallel<TSource>(this IEnumerable<TSource> enumerable, Action<TSource> action)
        {
            if (enumerable != null && enumerable.Any())
            {
                Parallel.ForEach(enumerable, item => action(item));
            }
        }
        

        /// <summary>
        /// 将集合转换成只读集合。
        /// </summary>
        /// <typeparam name="T">对象类型。</typeparam>
        /// <param name="enumerable">对象列表。</param>
        /// <returns>对象列表。</returns>
        public static IList<T> ToReadOnlyCollection<T>(this IEnumerable<T> enumerable)
        {
            return new ReadOnlyCollection<T>(enumerable.ToList());
        }
    }
}